package com.able.mmbs;

import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.able.mmbs.util.TempretureProcessTool;
import com.able.mmbs.util.TextConverter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@SuppressLint("MissingPermission")
public class MainActivity extends AppCompatActivity {

    String TAG = "MainActivity->";

    NavController navController;

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    private final int REQUEST_PERMISSION_CODE = 1001;

    String deviceAddress = "C2:D6:9B:6D:2B:18";
    String notifyServiceUUIDStr = "0000ffe5-0000-1000-8000-00805f9b34fb";
    //                           0000ffe8-0000-1000-8000-00805f9b34fb
    String notifyCharaUUIDStr = "0000ffe8-0000-1000-8000-00805f9b34fb";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);


        // 检查蓝牙开关
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            APP.toast("本机没有找到蓝牙硬件或驱动！", 0);
            finish();
            return;
        } else {
            if (!adapter.isEnabled()) {
                //直接开启蓝牙
                adapter.enable();
                //跳转到设置界面
                //startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 112);
            }
        }

        //检查是否支持BLE
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            APP.toast("系统不支持BLE", Toast.LENGTH_SHORT);
            finish();
        }

        // Make sure we have access coarse location enabled, if not, prompt the user to enable it
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("定位授权");
            builder.setMessage("请授予位置访问权限，以便此应用可以检测外围设备");
            builder.setPositiveButton(android.R.string.ok, null);
            builder.setOnDismissListener(dialog -> requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION));
            builder.show();
        }

        initPermission();

        // 声明一个BluetoothDevice变量为连接目标
        BluetoothDevice bluetoothDevice = adapter.getRemoteDevice(deviceAddress);
        // 声明一个BluetoothGatt变量用于BLE服务
        BluetoothGatt bluetoothGatt;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            bluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, true, gattCallback, TRANSPORT_LE);
        } else {
            bluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, true, gattCallback);
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        Log.i(TAG, "onCreateOptionsMenu: ...");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_debug) {
            navController.navigate(R.id.action_homeFragment_to_bleHomeFragment);
            return true;
        }

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    // 设置 BluetoothGattCallback 以处理 BLE 事件
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "connect successfully");
                // 连接建立成功
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // 连接断开后的操作
                Log.i(TAG, "disconected");
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 获取服务列表
                List<BluetoothGattService> services = gatt.getServices();
                // 对于每个服务，获取其所有特征
                for (BluetoothGattService service : services) {
                    List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                    // 对于每个特征，检查它是否支持读操作等等
                    for (BluetoothGattCharacteristic characteristic : characteristics) {
                        int properties = characteristic.getProperties();
                        if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                            // 属性为只读
                            Log.i(TAG, characteristic.getUuid().toString() + " -> read");
                        }
                        if ((properties & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                            // 属性为只写
                            Log.i(TAG, characteristic.getUuid().toString() + " -> write");
                        }
                        if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                            // 属性为可通知
                            gatt.setCharacteristicNotification(characteristic, true);
                            Log.i(TAG, characteristic.getUuid().toString() + " -> notification");
                        }
                    }
                }
                //订阅通知
//                gatt.setCharacteristicNotification(gatt
//                        .getService(notify_UUID_service).getCharacteristic(notify_UUID_chara),true);

                UUID notify_UUID_service = UUID.fromString(notifyServiceUUIDStr);
                UUID notify_UUID_chara = UUID.fromString(notifyCharaUUIDStr);

                //订阅通知
                gatt.setCharacteristicNotification(gatt.getService(notify_UUID_service).getCharacteristic(notify_UUID_chara), true);

            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            // 处理接收到的 BLE 数据
            byte[] value = characteristic.getValue();
            String dataHex = TextConverter.bytesToHex(value);
            Log.i(TAG, "rev: " + dataHex);
            Map<String, Object> values = TempretureProcessTool.getValues(dataHex);
            for (Map.Entry<String, Object> entry : values.entrySet()) {
                System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            // BLE 数据写入结束后的处理
        }
    };

    private void initPermission() {
        List<String> mPermissionList = new ArrayList<>();
        // Android 版本大于等于 12 时，申请新的蓝牙权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);
            //根据实际需要申请定位权限
            //mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            //mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), REQUEST_PERMISSION_CODE);
    }
}